package com.jiuyin.dianjing.ui.activity.community;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.CommentAdapter;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.CommentModel;
import com.jiuyin.dianjing.model.PostModel;
import com.jiuyin.dianjing.model.ThumbModel;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.activity.setting.SettingCollectionActivity;
import com.jiuyin.dianjing.ui.activity.setting.SettingMyHomePageActivity;
import com.jiuyin.dianjing.ui.fragment.community.PostFragment;
import com.jiuyin.dianjing.ui.fragment.homepage.HomepageSecond;
import com.jiuyin.dianjing.ui.fragment.main.FragmentFive;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ShareUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_MODEL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CLICK_NUM1;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMMENT_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CONTENT;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOPIC_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_USERID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.OSS_IMG_SHARPEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_ATTENTION_USER;
import static com.jiuyin.dianjing.model.PostModel.OWN_POSTS;

/**
 * 帖子详情
 */
public class PostDetailActivity extends BaseActivity {
    public static final int RC_FROM_COMMENT_ACTIVITY = 2;
    private static final int PRC_PHOTO_PREVIEW = 1;
    PostModel postModel;
    @BindView(R.id.iv_rightMenu)
    ImageView mImgRightMenu;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_follow)
    CheckedTextView tvFollow;
    @BindView(R.id.tv_detail_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.layout_nine_grid)
    BGANinePhotoLayout mPhotosSnpl;
    @BindView(R.id.tv_tag_desire)
    TextView tvTagDesire;
    @BindView(R.id.tv_tag_game)
    TextView tvTagGame;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tv_clicked)
    TextView tvClicked;
    @BindView(R.id.tv_thumb)
    CheckedTextView tvThumb;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.et_comment)
    EditText etComment;
    @BindView(R.id.iv_send)
    View ivSend;
    @BindView(R.id.srl_record_layout)
    SmartRefreshLayout mSrlRecordLayout;
    @BindView(R.id.tv_comment_title)
    TextView mCommentTitle;
    private CommentAdapter mCommentAdapter;
    private int mPageNum = PAGE_FIRST;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_post_detail;
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        postModel = (PostModel) bundle.getSerializable(KEY_POST);
        mCommentAdapter = new CommentAdapter(this, R.layout.item_comment);
        rvComment.setAdapter(mCommentAdapter);
        fetchComment();
    }

    private void fetchClickCount() {
        ApiResultCallback apiRequestCallback = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                int click_num = data.getAsInt();
                tvClicked.setText(String.valueOf(click_num));
            }

            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log(msg);
            }
        };
        HashMap<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, HelperApplication.getToken());
        map.put(KEY_TOPIC_ID, postModel.getTopic_id());
        JSONObject data = new JSONObject(map);
        ServerApi.post(ApiEnum.APP_addClickLog.getUrl(), data, null, null, null, apiRequestCallback);
    }

    private void fetchComment() {
        HashMap<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, HelperApplication.getToken());
        map.put(KEY_PAGE_NUM, mPageNum);
        map.put(KEY_TOPIC_ID, postModel.getTopic_id());
        JSONObject data = new JSONObject(map);
        ApiResultCallback apiRequestCallback = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                if (null != data && data.has(KEY_COMMENT_LIST)) {
                    LogUtil.log("appGetReplyList onSuccess = " + data.toString());
                    List<CommentModel> list = new Gson().fromJson(data.getAsJsonArray(KEY_COMMENT_LIST),
                            new TypeToken<List<CommentModel>>() {
                            }.getType());
                    if (null != list) {
                        int size = list.size();
                        if (0 != size) {
                            mCommentTitle.setText(R.string.comment_total_header);
                            onRefresh(list);
                        } else {
                            loadDataFinished();
                        }
                    }
                    if (data.has(KEY_CLICK_NUM1)) {
                        tvClicked.setText(data.get(KEY_CLICK_NUM1).getAsString());
                    }
                } else {
                    loadDataFinished();
                }
            }

            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log(msg);
            }
        };
        ServerApi.post(ApiEnum.APP_GET_REPLY_LIST.getUrl(), data, null, null, null, apiRequestCallback);
    }

    @Override
    protected void initView() {
        setTitle("帖子详情");
        mImgRightMenu.setImageResource(R.drawable.img_more);
        mImgRightMenu.setVisibility(View.VISIBLE);
        if (postModel != null && postModel.getHeader() != null) {
            StringBuilder url = new StringBuilder(postModel.getHeader());
            url.append(OSS_IMG_SHARPEN);
            Glide.with(this)
                    .load(url.toString())
                    .placeholder(R.drawable.img_header_placeholder)
                    .override(DisplayUtil.dp2px(this, 50))
                    .into(ivHead);
        }
        tvName.setText(postModel.getNickname());
        tvTime.setText(postModel.getCreate_time());
        setAttentionStatus(postModel.getIsAttention());
        if (postModel.getIsOneSelf().equals(OWN_POSTS)) {
            tvFollow.setVisibility(View.GONE);
        } else {
            tvFollow.setVisibility(View.VISIBLE);
        }
        tvFollow.setOnClickListener(v -> {
            HashMap<String, Object> params = new HashMap<>();
            params.put(KEY_TOKEN, HelperApplication.getToken());
            params.put(KEY_TARGETID, postModel.getUser_id());
            params.put(KEY_TYPE, tvFollow.isChecked() ? 0 : 1);
            params.put(KEY_ATTENTION_MODEL, VALUE_ATTENTION_USER);
            JSONObject json = new JSONObject(params);
            ApiResultCallback apiResultCallback = new ApiResultCallback() {
                @Override
                public void onSuccess(JsonObject data) {
                    tvFollow.setEnabled(true);
                    EventBus.getDefault().post(new RefreshEvent(PostFragment.class.getSimpleName()));
                    EventBus.getDefault().post(new RefreshEvent(FragmentFive.class.getSimpleName()));
                    setAttentionStatus(data.get("isAttention").getAsInt());
                }

                @Override
                public void onFail(String msg) {
                    tvFollow.setEnabled(true);
                    ToastUtil.showShort(msg);
                }

                @Override
                public void onError(String msg) {
                    tvFollow.setEnabled(true);
                    LogUtil.log(msg);
                }
            };
            tvFollow.setEnabled(false);
            ServerApi.post(ApiEnum.APP_ADD_ATTENTION_LOG.getUrl(), json, null,
                    progress, d -> addDisposable(d), apiResultCallback);
        });
        tvTitle.setText(postModel.getTitle());
        tvContent.setText(postModel.getContent());
        String genre_tag = postModel.getGenre_tag();
        if (!TextUtils.isEmpty(genre_tag)) {
            tvTagDesire.setText(getString(R.string.tag, genre_tag));
        }
        String game_tag = postModel.getGame_tag();
        if (!TextUtils.isEmpty(game_tag)) {
            tvTagGame.setText(getString(R.string.tag, game_tag));
        }
        tvShare.setText(String.valueOf(postModel.getShare_num()));
        tvThumb.setText(postModel.getThumb_num());
        tvThumb.setChecked(postModel.getIsThumb() == 1);
        tvThumb.setOnClickListener(v -> {
            ApiResultCallback apiResultCallback = new ApiResultCallback() {
                @Override
                public void onSuccess(JsonObject data) {
                    ThumbModel thumbModel = new Gson().fromJson(data, ThumbModel.class);
                    tvThumb.setChecked(thumbModel.isThumb == 1);
                    tvThumb.setText(thumbModel.thumb_num);
                    tvThumb.setEnabled(true);
                    EventBus.getDefault().post(new RefreshEvent(PostFragment.class.getSimpleName()));
                    EventBus.getDefault().post(new RefreshEvent(SettingCollectionActivity.class.getSimpleName()));
                }

                @Override
                public void onFail(String msg) {
                    ToastUtil.showShort(msg);
                    tvThumb.setEnabled(true);
                }

                @Override
                public void onError(String msg) {
                    tvThumb.setEnabled(true);
                    LogUtil.log(msg);
                }
            };
            HashMap<String, Object> map = new HashMap<>();
            map.put(KEY_TOKEN, HelperApplication.getToken());
            map.put(KEY_TARGETID, postModel.getTopic_id());//评论或者 帖子主键
            map.put(KEY_TYPE, tvThumb.isChecked() ? 0 : 1);//0 取消点赞 1 点赞
            JSONObject json = new JSONObject(map);
            tvThumb.setEnabled(false);
            ServerApi.post(ApiEnum.APP_TOPIC_THUMB.getUrl(), json, null, progress, d -> addDisposable(d), apiResultCallback);
        });
        tvClicked.setText(postModel.getClick_num());
        tvComment.setText(postModel.getComment_num());
        if (postModel.getPhoto() != null) {
            mPhotosSnpl.setDelegate(new BGANinePhotoLayout.Delegate() {
                @Override
                public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                    photoPreviewWrapper();
                }

                /**
                 * 图片预览
                 */
                private void photoPreviewWrapper() {
                    BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder =
                            new BGAPhotoPreviewActivity.IntentBuilder(PostDetailActivity.this);
                    if (mPhotosSnpl.getItemCount() == 1) {
                        // 预览单张图片
                        photoPreviewIntentBuilder.previewPhoto(mPhotosSnpl.getCurrentClickItem());
                    } else if (mPhotosSnpl.getItemCount() > 1) {
                        // 预览多张图片
                        photoPreviewIntentBuilder.previewPhotos(mPhotosSnpl.getData())
                                .currentPosition(mPhotosSnpl.getCurrentClickItemPosition()); // 当前预览图片的索引
                    }
                    startActivity(photoPreviewIntentBuilder.build());
                }

                @Override
                public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                    ninePhotoLayout.setIsExpand(true);
                    ninePhotoLayout.flushItems();
                }
            });
            mPhotosSnpl.setData((ArrayList<String>) postModel.getPhoto());
        }
        mImgRightMenu.setOnClickListener(v -> {
            ShareUtil shareUtil = ShareUtil.getInstance(PostDetailActivity.this, postModel.getHeader(), postModel.getTitle());
            if (postModel.getPhoto().size() > 0) {
                shareUtil.setImageUrl(postModel.getPhoto().get(0));
            }
            shareUtil.initShare();
            shareUtil.open();
        });
        ivSend.setOnClickListener(v -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put(KEY_TOKEN, HelperApplication.getToken());
            map.put(KEY_CONTENT, etComment.getText().toString());
            map.put(KEY_TOPIC_ID, postModel.getTopic_id());
            JSONObject json = new JSONObject(map);
            ApiResultCallback resultCallback = new ApiResultCallback() {
                @Override
                public void onSuccess(JsonObject data) {
                    IMEUtil.hideInputMethod(PostDetailActivity.this);
                    int com = Integer.parseInt(tvComment.getText().toString());
                    String newCom = String.valueOf(com + 1);
                    tvComment.setText(newCom);
                    mPageNum = PAGE_FIRST;
                    fetchComment();
                    EventBus.getDefault().post(new RefreshEvent(SettingCollectionActivity.class.getSimpleName()));
                    EventBus.getDefault().post(new RefreshEvent(HomepageSecond.class.getSimpleName()));
                    EventBus.getDefault().post(new RefreshEvent(PostFragment.class.getSimpleName()));
                }

                @Override
                public void onFail(String msg) {
                    LogUtil.log(msg);
                }

                @Override
                public void onError(String msg) {
                    LogUtil.log(msg);
                }
            };
            ServerApi.post(ApiEnum.APP_COMMENT_TOPIC.getUrl(), json, null, progress, d -> addDisposable(d), resultCallback);
            etComment.setText("");
        });

        mSrlRecordLayout.setEnableRefresh(false);//是否启用下拉刷新功能
        mSrlRecordLayout.setEnableAutoLoadMore(true);
        mSrlRecordLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                fetchComment();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPageNum = PAGE_FIRST;
                fetchComment();
            }
        });
    }

    private void setAttentionStatus(int isAttention) {
        if (isAttention == 1) {
            tvFollow.setChecked(true);
            tvFollow.setText("取消关注");
        } else {
            tvFollow.setChecked(false);
            tvFollow.setText("关注作者");
        }
    }

    public void onRefresh(List<CommentModel> models) {
        int size = models.size();
        if (PAGE_FIRST == mPageNum) {
            mCommentAdapter.refresh(models);
            mSrlRecordLayout.finishRefresh();
            mSrlRecordLayout.resetNoMoreData();
        } else {
            if (0 != size) {
                mCommentAdapter.loadMore(models);
            }
        }
        if (size < PAGE_NUM) {
            mSrlRecordLayout.finishLoadMoreWithNoMoreData();
        } else {
            mSrlRecordLayout.finishLoadMore();
        }
        mPageNum++;
    }

    /**
     * 处理加载状态
     */
    protected void loadDataFinished() {
        mSrlRecordLayout.finishRefresh();
        if (0 == getRecycleViewSize()) {
            mSrlRecordLayout.finishLoadMore();
        } else {
            mSrlRecordLayout.finishLoadMoreWithNoMoreData();
        }
    }

    /**
     * 得到大小
     *
     * @return
     */
    protected int getRecycleViewSize() {
        if (null != mCommentAdapter) {
            return mCommentAdapter.getItemCount();
        } else {
            return 0;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RC_FROM_COMMENT_ACTIVITY) {
                mPageNum = PAGE_FIRST;
                fetchComment();
            }
        }
    }

    @OnClick({R.id.iv_head})
    public void onViewClicked(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.iv_head:
                Bundle bundle = new Bundle();
                bundle.putString(KEY_USERID, postModel.getUser_id());
                goTargetActivity(SettingMyHomePageActivity.class, bundle);
                break;
            default:
                break;
        }
    }
}
